#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqList.h"

void SeqListInit(SeqList* ps)
{
	assert(ps);
	ps->data = (SLDataType*)malloc(CAP_DEF*sizeof(SLDataType));

	if (ps->data == NULL)
		perror("malloc fail");

	ps->size = 0;
	ps->capacity = CAP_DEF;
}

void CheckSLCapacity(SeqList* ps)
{
	if (ps->size == ps->capacity)
	{
		SLDataType* ptr = (SLDataType*)realloc(ps->data,(ps->capacity) * 2);
		if (ptr == NULL)
		{
			perror("realloc");
		}
		else
		{
			ps->data = ptr;
			ptr = NULL;
		}
	}

	ps->capacity *= 2;
}

void SeqListPrint(SeqList* ps)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->data[i]);
	}
	printf("\n");
}

void SeqListPushBack(SeqList* ps, SLDataType x)
{
	//assert(ps);
	//CheckSLCapacity(ps);
	//ps->data[ps->size] = x;
	//ps->size++;
	SeqListInsert(ps, ps->size, x);
}

void SeqListPopBack(SeqList* ps)
{
	//assert(ps);
	//assert(ps->size > 0);

	//ps->size--;
	SeqListErase(ps, ps->size-1);
}

void SeqListPushFront(SeqList* ps, SLDataType x)
{
	assert(ps);

	//CheckSLCapacity(ps);
	//int end = ps->size-1;
	//while (end >= 0)
	//{
	//	ps->data[end+1] = ps->data[end];
	//	end--;
	//}

	//ps->data[0] = x;
	//ps->size++;
	SeqListInsert(ps, 0, x);

}

void SeqListPopFront(SeqList* ps)
{
	//assert(ps);
	//assert(ps->size > 0);
	//int begin = 0;
	//while (begin < ps->size - 1)
	//{
	//	ps->data[begin] = ps->data[begin + 1];
	//	begin++;
	//}
	//ps->size--;
	SeqListErase(ps, 0);
}

size_t SeqListFind(SeqList* ps, SLDataType x)
{
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		if (ps->data[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SLDestory(SeqList* ps)
{
	assert(ps);
	free(ps->data);
	ps->data = NULL;
	ps->capacity = ps->size = 0;
}

void SeqListInsert(SeqList* ps, size_t pos, SLDataType x)
{
	assert(ps);
	CheckSLCapacity(ps);
	int end = ps->size;
	while (end > pos)
	{
		ps->data[end] = ps->data[end - 1];
		end--;
	}
	ps->data[pos] = x;
	ps->size++;
}

void SeqListErase(SeqList* ps, size_t pos)
{
	assert(ps);
	assert(ps->size > 0);
	size_t begin = pos + 1;
	while (begin < ps->size)
	{
		ps->data[begin - 1] = ps->data[begin];
		begin++;
	}
	ps->size--;

}